// permission.ts,此文件在main.js中直接导入即可，这边的思路是仿照的element-admin
import { RouteRecordRaw } from 'vue-router';
import router from './index';
// import store from '../store';
import { getToken, removeToken } from '@/utils/auth';

import axios from 'axios'
import 'nprogress/nprogress.css' // progress bar style
// @ts-ignore
import NProgress from 'nprogress' // progress bar
// 全局配置
NProgress.configure({
  minimum: 0.1,
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  // color: 'red',
})

const getUserResourceTree = () => {
  return axios.get<Array<RouteRecordRaw>>('./menu.json')
}

const dealRoutes = (route: Array<RouteRecordRaw>, parent = "") => {
  route.forEach(item => {
    if (item.children) {
      dealRoutes(item.children, item.path)
    } else {
      // router.addRoute(parent, {
      //   ...item,
      //   path: parent + item.path,
      //   component: () => import(item.componentPath)
      // })
    }
  })
}
router.beforeEach(async (to, from, next) => {
  const token = getToken();
  console.log(token)
  NProgress.start();
  // 如果已经处于登录状态，跳到登录页重定向到首页
  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (!localStorage.getItem('authorized')) {
        try {
          // 因为setAccessRoutes返回一个promise，await可获取结果
          const menuRet = await getUserResourceTree()
          if (menuRet.status === 200) {
            menuRet.data.forEach((item) => {
              (item)
            })
          }
          next({ ...to, replace: true })
        } catch (e) {
          removeToken()
          next({ path: '/login', query: { old: to.path } })
          NProgress.done()
        }
      } else {
        next()
        // 全屏参数判断该页面是否全屏
        // if (!screenfull.isEnabled) return
        // if (to.meta && to.meta.fullScreen) {
        //   screenfull.request().catch(() => null)
        // } else {
        //   if (screenfull.isFullscreen) {
        //     screenfull.exit()
        //   }
        // }
      }
    }
  } else {// 未登录
    // decodeURIComponent("%2Fsystem%2Frole")
    // "/system/role"
    // encodeURIComponent("/")
    // "%2F"
    (to.path !== '/login') ? next({ path: '/login', query: { old: to.path } }) : next();
  }
})

router.afterEach(() => {
  NProgress.done()
})

